// pages/order/create-order.js
import OrderService from '../../../service/OrderService';
import CommonService from '../../../service/CommonService';
import { throttle } from '../../../utils/util.js';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    productTypes: app.globalData.productTypes,
    selectType: {},
    errMsg: '',
    order: {},
    planFiles:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.orderService = new OrderService()
    this.commonService = new CommonService();
    if(options.id){
      this.getOrderById(options.id);
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const { chooseCity } = app.globalData;
    const { order } = this.data;
    if (chooseCity.id) {
      order.city = chooseCity;
      order.adcode = chooseCity.id;
      this.setData({ order });
    }
  },
  setFieldValue: function (field, value) {
    const { order } = this.data;
    order[field] = value;
    this.setData({ order });
  },
  onOrderTitleChange: function(e){
    this.setFieldValue("orderTitle", e.detail.value);
  },
  onOrderDescChange: function(e){
    this.setFieldValue("orderDesc", e.detail.value);
  },
  onOrderTypeChange: function (e) {
    this.setFieldValue("orderType", e.detail.id);
    const selectType = this.getProductType(e.detail.id);
    this.setData({ selectType });
  },
  /**
   * 方案图片变化事件
   */
  onPlanFilesChange: function (e) {
    const images = e.detail.images.map(fileUrl => ({ fileUrl }));
    this.setFieldValue("planFiles", images);
  },
  /**
   * 交货日期变化监听
   */
  onEndTimeChange: function (e) {
    this.setFieldValue("endTime", e.detail.date);
  },
  onBudgetMoneyChange: function(e){
    this.setFieldValue("budgetMoney", e.detail.value);
  },
  onThankMoneyChange: function (e) {
    this.setFieldValue("thankMoney", e.detail.value);
  },
  /**跳转到选择订单行政区域界面 */
  onLocationTap: function () {
    throttle(function (e) {
      wx.navigateTo({
        url: '/pages/citys/citys'
      })
    }, 1000)();
  },
  onLocation: function (e) {
    const _ = this;
    const { order } = this.data;
    wx.chooseLocation({
      success: function (res) {
        order.linkAddr = res.address;
        order.lng = res.longitude;
        order.lat = res.latitude;
        _.setData({ order });
      }
    })
  },
  onIsSecurity: function (e) {
    const { value } = e.detail;
    this.setFieldValue('isSecurity', value.join(""));
  },
  onIsService: function (e) {
    const { value } = e.detail;
    this.setFieldValue('isService', value.join(""));
  },
  validForm: function (form) {
    if (!form.orderTitle) {
      this.setData({ errMsg: '订单标题不能为空' })
      return false;
    }
    if (!form.orderDesc) {
      this.setData({ errMsg: '订单说明不能为空' })
      return false;
    }
    if (!form.orderType) {
      this.setData({ errMsg: '请选择订单类型' })
      return false;
    }
    if (!form.endTime) {
      this.setData({ errMsg: '请选择交货日期' })
      return false;
    }
    if (!form.budgetMoney) {
      this.setData({ errMsg: '请输入预算金额' })
      return false;
    }else{
      const {selectType} = this.data;
      if (form.budgetMoney < selectType.money){
        this.setData({ errMsg: '预算金额不能低于' + selectType.money+'元' })
        return false;
      }
    }
    if (form.thankMoney && form.thankMoney > form.budgetMoney*0.1){
      this.setData({ errMsg: '感谢费不能高于预算金额的10%' })
      return false;
    }
    if (!form.isSecurity) {
      this.setData({ errMsg: '请阅读担保交易协议' })
      return false;
    }
    if (!form.isService) {
      this.setData({ errMsg: '请阅读付款方式协议' })
      return false;
    }
    this.setData({ errMsg: '' });
    return true;
  },
  formSubmit: function(e){
    const _ = this;
    const { order } = this.data;
    if(!this.validForm(order)){
      return;
    }
    const param = {
      "id": order.id,
      "orderTitle": order.orderTitle,
      "orderDesc": order.orderDesc,
      "orderType": order.orderType,
      "endTime": order.endTime,
      "budgetMoney": order.budgetMoney,
      "thankMoney": order.thankMoney,
      // "linkMan": order.linkMan,
      // "linkPhone": order.linkPhone,
      "linkAddr": order.linkAddr,
      "isSecurity": order.isSecurity,
      "isService": order.isService,
      "adcode": order.adcode,
      "lat": order.lat,
      "lng": order.lng,
      "planFiles": order.planFiles
    }
    if(param.id){
      this.orderService.update(param).then(function (res) {
        console.log(res);
        if(res.status == 0){
          wx.showToast({
            title: '修改成功',
            success: function(){
              wx.navigateBack()
            }
          })
        }else{
          wx.showToast({
            title: res.message,
          })
        }
      });
    }else{
      this.orderService.save(param).then(function (res) {
        console.log(res);
        if (res.status == 0) {
          const { orderScore } = app.globalData.setting;
          _.commonService.active(5).then(function (res) {
            if (res.status == 0) {
              wx.showModal({
                title: '订单创建成功',
                content: `你获得${orderScore}枚救兵勋章`,
                showCancel: false,
                confirmText: '知道了',
                confirmColor: '#0f9bc1',
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateBack()
                  }
                }
              })
            }
          });
        } else {
          wx.showToast({
            title: res.message,
          })
        }
      });
    }
  },
  lookProtocol: function(e){
    const type = e.target.dataset.type;
    throttle(function () {
      wx.navigateTo({
        url: '/packageUser/pages/protocol/protocol?type='+type
      })
    }, 1000)()
  },
  getProductType: function(id){
    const { productTypes } = this.data;
    for(let i = 0; i < productTypes.length; i++){
      if (productTypes[i].id == id){
        return productTypes[i];
      }
    }
    return null;
  },
  getOrderById: function(id){
    const _ = this;
    this.orderService.getOrderById(id).then(res => {
      console.log(res);
      if(res.status == 0){
        const selectType = _.getProductType(res.data.orderType);
        _.setData({ order: res.data, selectType });
      }
    })
  }
})